<template>
  <el-row class="mx__20 px-20 bg-white">
    <el-col class="current-content-style">
      <el-row class="py-20" :gutter="20">
        <el-col :span="8">
          <el-input placeholder="输入地域名称可增加子项，修改、删除选中地域" v-model.trim="text"> </el-input>
        </el-col>
        <el-col :span="16">
          <el-button plain type="primary" @click="addRegionHandler">增加</el-button>
          <el-button plain type="warning" @click="editRegionHandler">编辑</el-button>
          <el-button plain type="danger" @click="deleteRegionHandler">删除</el-button>
        </el-col>
        <el-col :span="24">
          <el-tree
            :data="data"
            show-checkbox
            :check-on-click-node="true"
            :default-expanded-keys="defaultExpandedKeys"
            node-key="id"
            ref="tree"
            :highlight-current="true"
            :props="defaultProps"
            @check="handleCheck"
            :lazy="true"
            :load="loadNode"
            :check-strictly="true"
            :accordion="false"
            :indent="30"
          >
          </el-tree>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
// 区域管理
import { deleteRegion, addRegion, queryRootRegionAll, queryChildrenRegionAll, editRegion } from '@/config/api'

export default {
  created() {
    this.queryRootRegionAllHandler()
  },
  watch: {
    level_1(val) {
      // console.log(val)
      let regionArr = []
      let idArr = []
      val.forEach(el => {
        // 这个对象的属性，和defaultProps的配置有关联，label对应的值，要是这个对象里面的地名的属性
        // level属性，用来判断是几级地域
        let obj = { id: el.regionId, regionName: el.regionName, level: 1 }
        regionArr.push(obj)
        idArr.push(el.regionId)
      })
      this.data = regionArr
      this.defaultExpandedKeys = idArr
    }
  },

  methods: {
    // 编辑地域名称
    editRegionHandler() {
      if (this.checkedKeys.length === 0) {
        this.$alert('请选择一个要编辑的地域')
        this.text = ''
        return
      }
      if (this.checkedKeys.length > 1) {
        this.$alert('一次只能选择一个要编辑的地域')
        this.text = ''
        return
      }
      console.log(this.checkedKeys, this.checkedNodesLevel)
      editRegion({ regionId: this.checkedKeys[0], regionName: this.text })
        .then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '修改地域名称成功'
            })
            this.queryRootRegionAllHandler()
          } else {
            this.$message({
              type: 'error',
              message: '修改地域名称失败'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'warning',
            message: '服务器异常，请联系管理员'
          })
        })
      this.text = ''
    },

    // 删除一个节点tree
    deleteRegionHandler() {
      if (this.checkedKeys.length === 0) {
        this.$alert('请选择一个要删除的地域')
        return
      }
      if (this.checkedKeys.length > 1) {
        this.$alert('一次只能选择一个要删除的地域')
        return
      }
      let regionId = this.checkedKeys[0]
      deleteRegion({ regionId }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.queryRootRegionAllHandler()
        } else {
          this.$message({
            message: '删除失败',
            type: 'error'
          })
        }
      })
    },
    // 动态加载子tree
    loadNode(node, resolve) {
      console.log(node)
      // console.log(resolve)

      this.getChildReginHandler(node.data.id).then(res => {
        let level = node.data.level + 1
        let regionArr = []
        res.forEach(el => {
          let obj = { id: el.regionId, regionName: el.regionName, level }
          regionArr.push(obj)
        })
        resolve(regionArr)
      })
    },
    // 选择地域时
    handleCheck(data, obj) {
      console.log(data) // 渲染的数据
      console.log(obj) // tree组件里面的DOM节点对象
      if (obj.checkedKeys.length !== 0) {
        this.checkedKeys = obj.checkedKeys // 存储选中的 [id]
        this.checkedNodesLevel = obj.checkedNodes[0].level // 选择的节点对象的level
      } else {
        this.checkedKeys = obj.checkedKeys // 存储选中的[]
        this.checkedNodesLevel = obj?.checkedNodes[0]?.level // 选择的节点对象 undefind
      }
      console.log(this.checkedKeys, this.checkedNodesLevel)
    },

    // 查询所有根地域
    queryRootRegionAllHandler() {
      queryRootRegionAll().then(res => {
        if (res.code === 200) {
          console.log(res)
          this.level_1 = res.data
        } else {
          this.$message({
            message: '查询根地域失败',
            type: 'error'
          })
        }
      })
    },
    // 添加地域
    addRegionHandler() {
      let regionName = this.text
      let regionParentId
      if (!regionName) {
        this.$message({
          message: '请输入地区名称',
          type: 'info'
        })
        return
      }

      if (this.checkedNodesLevel === 3) {
        this.$message({
          message: '只能给1级、2级地域添加子地域',
          type: 'error'
        })
        this.text = ''
        return
      }
      if (this.checkedKeys.length > 1) {
        this.$message({
          message: '只能给一个地域添加子级地域',
          type: 'error'
        })
        return
      } else if (this.checkedKeys.length === 1) {
        regionParentId = this.checkedKeys[0]
      } else {
        regionParentId = null
      }

      addRegion({ regionName, regionParentId }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '添加地域成功',
            type: 'success'
          })
          this.queryRootRegionAllHandler()
        } else {
          this.$message({
            message: '添加地域失败',
            type: 'error'
          })
        }
      })
      this.text = ''
    },
    // 获取一个节点的子级
    getChildReginHandler(id) {
      return queryChildrenRegionAll({ regionParentId: id }).then(res => {
        // console.log(res)
        if (res.code === 200) {
          return res.data
        }
      })
    }
  },

  data() {
    return {
      checkedKeys: [], //选择的节点的key，对应节点对象(后端)的ID
      text: '',
      checkedNodesLevel: 1, // 选择的节点级别
      level_1: [], //存储1级地域
      data: [], //渲染tree组件的数据
      defaultProps: {
        children: 'children',
        label: 'regionName'
      },
      defaultExpandedKeys: [] // 默认展开的root树的数组
    }
  }
}
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
